from django.db                    import models
from django.db.models             import signals
from django.utils.translation     import ugettext_lazy as _
from django.utils.datastructures  import SortedDict
from sitepal.sitebase.managers    import ResourceManager
from sitepal.sitebase.models      import Resource
from sitepal.sitemenu.models.util import get_from_cache_or_load

class MenuManager(ResourceManager):
    _cache_threshold = 512
    _menu_cache      = SortedDict()

    @classmethod
    def _update_cache(cls,sender,instance,created,**kwargs):
        if not created:
            if instance.name in cls._menu_cache:
                cls._menu_cache[instance.name] = instance
            else:
                for name,menu in cls._menu_cache.items():
                    if menu.pk == instance.pk:
                        del cls._menu_cache[name]
                        cls._menu_cache[instance.name] = instance
                        break
        elif len(cls._menu_cache) < cls._cache_threshold:
            cls._menu_cache[instance.name] = instance

    def _lookup_by_name(self,name):
        return self.get(name__exact=name)

    def get_by_name(self,name=None):
        return get_from_cache_or_load(name or 'navigation',self._menu_cache,self._lookup_by_name,
                                      self._cache_threshold)

class Menu(Resource):
    title       = models.CharField(_("title"),max_length=100)
    description = models.TextField(_("description"),blank=True,null=True)
    objects     = MenuManager()

    class Meta(Resource.Meta):
        verbose_name        = _('menu')
        verbose_name_plural = _('menus')
        unique_together     = ('site','name')
        app_label           = 'sitemenu'

signals.post_save.connect(MenuManager._update_cache,sender=Menu)

